package com.bailiban.user.controller;

import com.bailiban.common.entity.Result;
import com.bailiban.common.entity.StatusCode;
import com.bailiban.common.util.JwtUtil;
import com.bailiban.user.entity.Admin;
import com.bailiban.user.entity.User;
import com.bailiban.user.service.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhulang
 * @Classname UserController
 * @Description UserController
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;

    @GetMapping("{id}")
    public Result findById(@PathVariable String id) {
        User user = userService.findById(id);
        return new Result(true, StatusCode.OK, "查询成功", user);
    }

    @PostMapping("sms/{phone}")
    public Result sendSms(@PathVariable String phone) {
        userService.sendSms(phone);
        return new Result(true, StatusCode.OK, "发送成功");
    }

    @PostMapping("regist/{code}")
    public Result regist(@RequestBody User user, @PathVariable String code) {
        userService.regist(user, code);
        return new Result(true, StatusCode.OK, "注册成功");
    }

    @PostMapping("login")
    public Result login(@RequestBody Map<String, String> map) {
        String mobile = map.get("mobile");
        String password = map.get("password");
        User user = userService.login(mobile, password);
        if (user == null) {
            return new Result(false, StatusCode.LOGINERROR, "登录失败");
        }
        String token = jwtUtil.createJWT(user.getId(), user.getLoginname(), "user");
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("token", token);
        hashMap.put("loginname", user.getLoginname());
        hashMap.put("image", user.getImage());
        user.setLastdate(user.getUpdatedate());
        user.setUpdatedate(new Date());
        userService.update(user);
        return new Result(true, StatusCode.OK, "登录成功", hashMap);

    }

    @DeleteMapping("{id}")
    public Result delete(@PathVariable String id) {
        //前端请求微服务时需要添加头信息Authorization ,内容为Bearer+空格+token
        Claims claims = (Claims) request.getAttribute("claims_roles");
        if ("admin".equals(claims.get("roles"))) {
            userService.delete(id);
            return new Result(true, StatusCode.OK, "删除成功");

        }
        return new Result(false, StatusCode.ACCESSERROR, "权限不足");

    }
}
